package com.redis.server.cn.utils;

import com.alibaba.fastjson.JSONObject;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

/**
 * Created by yunan on 2017/4/28.
 * 通用工具类
 */
public class CommUtils {
    /**
     * 空对象判断
     * @param obj
     * @return
     */
    public static boolean isNullObject(Object obj){
        boolean result= false;
        if(null==obj||"".equals(obj)){
            result = true;
        }
        return  result;
    }

    /**
     * 获取当前时间字符串 格式 yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static String getCurrentDate(){
        return  dateToStr(LocalDateTime.now(),"yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 时间转字符串
     * @param localDateTime
     * @param formateStr
     * @return
     */
    public static String dateToStr(LocalDateTime localDateTime,String formateStr){

        return  localDateTime.format(DateTimeFormatter.ofPattern(formateStr));
    }

    /**
     * 字符串转时间
     * @param dateString
     * @return
     */
    public static LocalDateTime stringToDate(String dateString){
        return  LocalDateTime.parse(dateString,DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    /**
     * 获取jsonobject属性
     * @param jsonObject
     * @return
     */
    public static String[] getJsonKeys(JSONObject jsonObject){
        String[] result = new String[jsonObject.keySet().size()];
        jsonObject.keySet().toArray(result);
        return  result;
    }

    /**
     * list转数组
     * @param source
     * @return
     */
    public static <T> T[] listToArray(List<T> source){
        T[] result = (T[]) new Object[source.size()];
        result = source.toArray(result);
        return  result;
    }

    /**
     * md5 加密
     * @param source 原始字符串
     * @param salt 盐
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String string2MD5(String source,String salt) throws NoSuchAlgorithmException {
        source = source + salt;
        MessageDigest md5 = MessageDigest.getInstance("MD5");

        char[] charArray = source.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++)
            byteArray[i] = (byte) charArray[i];
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }

            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }
}
